// 主应用入口

// 页面路由配置
const pages = {
    'work-plan': {
        title: '工作进度计划',
        icon: 'fas fa-tasks',
        load: loadWorkPlanPage
    },
    'outsource-list': {
        title: '外发清单查询',
        icon: 'fas fa-list',
        load: loadOutsourceListPage
    },
    'data-query': {
        title: '数据查询',
        icon: 'fas fa-search',
        load: loadDataQueryPage
    },
    'steel-mesh': {
        title: '钢网追踪',
        icon: 'fas fa-th',
        load: loadSteelMeshPage
    },
    'fixture': {
        title: '治具追踪',
        icon: 'fas fa-tools',
        load: loadFixturePage
    },
    'sop': {
        title: 'SOP签核追踪',
        icon: 'fas fa-file-alt',
        load: loadSOPPage
    },
    'import-export': {
        title: '导入导出',
        icon: 'fas fa-exchange-alt',
        load: loadImportExportPage
    }
};

// 当前页面
let currentPage = 'work-plan';

// 初始化应用
document.addEventListener('DOMContentLoaded', function() {
    initApp();
    loadPage('work-plan');
});

// 初始化应用
function initApp() {
    // 绑定导航链接事件
    document.querySelectorAll('.nav-link').forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const page = this.dataset.page;
            if (page && pages[page]) {
                loadPage(page);
            }
        });
    });

    // 绑定菜单切换事件（移动端）
    const drawerToggle = document.getElementById('drawer');
    if (drawerToggle) {
        drawerToggle.addEventListener('change', function() {
            if (!this.checked) {
                // 菜单关闭时的处理
            }
        });
    }

    // 自动检查延期项目
    setInterval(checkOverdueItems, 60000); // 每分钟检查一次
}

// 加载页面
function loadPage(pageName) {
    if (!pages[pageName]) {
        showMessage('页面不存在', 'error');
        return;
    }

    currentPage = pageName;
    const page = pages[pageName];
    const mainContent = document.getElementById('main-content');
    
    // 更新导航激活状态
    updateNavigation(pageName);
    
    // 显示加载状态
    showLoading(mainContent, `正在加载${page.title}...`);
    
    // 加载页面内容
    try {
        page.load(mainContent);
        
        // 更新页面标题
        document.title = `${page.title} - 工作计划追踪系统`;
        
        // 关闭移动端菜单
        const drawer = document.getElementById('drawer');
        if (drawer && window.innerWidth < 1024) {
            drawer.checked = false;
        }
        
    } catch (error) {
        console.error('页面加载失败:', error);
        hideLoading(mainContent);
        mainContent.innerHTML = `
            <div class="alert alert-error">
                <span>页面加载失败，请刷新页面重试</span>
            </div>
        `;
    }
}

// 更新导航激活状态
function updateNavigation(activePage) {
    document.querySelectorAll('.nav-link').forEach(link => {
        link.classList.remove('active');
        if (link.dataset.page === activePage) {
            link.classList.add('active');
        }
    });
}

// 创建页面标题
function createPageTitle(title, icon) {
    return `
        <div class="flex items-center mb-6">
            <i class="${icon} text-2xl mr-3 text-primary"></i>
            <h1 class="text-2xl font-bold">${title}</h1>
        </div>
    `;
}

// 创建工具栏
function createToolbar(buttons) {
    return `
        <div class="toolbar">
            <div class="btn-group">
                ${buttons.join('')}
            </div>
            <div class="search-box">
                <input type="text" class="search-input" placeholder="搜索..." id="search-input">
                <button class="btn btn-primary" onclick="handleSearch()">
                    <i class="fas fa-search"></i>
                </button>
            </div>
        </div>
    `;
}

// 创建表格
function createTable(headers, data, actions = []) {
    if (!data || data.length === 0) {
        return `
            <div class="card">
                <div class="text-center py-8 text-gray-500">
                    <i class="fas fa-inbox text-4xl mb-2"></i>
                    <p>暂无数据</p>
                </div>
            </div>
        `;
    }

    return `
        <div class="table-container">
            <table class="table table-zebra w-full">
                <thead>
                    <tr>
                        ${headers.map(header => `<th>${header}</th>`).join('')}
                        ${actions.length > 0 ? '<th>操作</th>' : ''}
                    </tr>
                </thead>
                <tbody>
                    ${data.map(item => `
                        <tr>
                            ${headers.map(header => {
                                const key = header.toLowerCase().replace(/\s+/g, '');
                                const value = item[key] || item[header] || '-';
                                return `<td>${value}</td>`;
                            }).join('')}
                            ${actions.length > 0 ? `
                                <td>
                                    <div class="btn-group">
                                        ${actions.map(action => `
                                            <button class="btn btn-sm btn-${action.type}" 
                                                    onclick="${action.handler}('${item.id}')">
                                                <i class="fas fa-${action.icon}"></i>
                                            </button>
                                        `).join('')}
                                    </div>
                                </td>
                            ` : ''}
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>
    `;
}

// 创建表单输入
function createFormInput(label, name, type = 'text', value = '', options = {}) {
    const { required = false, placeholder = '', options: selectOptions } = options;
    
    let inputHtml = '';
    if (type === 'select' && selectOptions) {
        inputHtml = `
            <select class="select select-bordered w-full" name="${name}" ${required ? 'required' : ''}>
                <option value="">请选择</option>
                ${selectOptions.map(opt => `
                    <option value="${opt.value}" ${value === opt.value ? 'selected' : ''}>
                        ${opt.text}
                    </option>
                `).join('')}
            </select>
        `;
    } else if (type === 'textarea') {
        inputHtml = `
            <textarea class="textarea textarea-bordered w-full" 
                      name="${name}" 
                      placeholder="${placeholder}"
                      ${required ? 'required' : ''}>${value}</textarea>
        `;
    } else {
        inputHtml = `
            <input type="${type}" 
                   class="input input-bordered w-full" 
                   name="${name}" 
                   value="${value}"
                   placeholder="${placeholder}"
                   ${required ? 'required' : ''}>
        `;
    }
    
    return `
        <div class="form-group">
            <label class="form-label">${label}${required ? ' <span class="text-red-500">*</span>' : ''}</label>
            ${inputHtml}
        </div>
    `;
}

// 处理搜索
function handleSearch() {
    const searchInput = document.getElementById('search-input');
    const query = searchInput?.value?.trim() || '';
    
    if (currentPage && pages[currentPage].search) {
        pages[currentPage].search(query);
    }
}

// 显示确认对话框
function showConfirmDialog(message, onConfirm, onCancel) {
    showConfirm(message, onConfirm, onCancel);
}

// 显示成功消息
function showSuccess(message) {
    showMessage(message, 'success');
}

// 显示错误消息
function showError(message) {
    showMessage(message, 'error');
}

// 显示警告消息
function showWarning(message) {
    showMessage(message, 'warning');
}

// 显示信息消息
function showInfo(message) {
    showMessage(message, 'info');
}

// 全局函数绑定到window对象
window.handleSearch = handleSearch;
window.showConfirmDialog = showConfirmDialog;
window.showSuccess = showSuccess;
window.showError = showError;
window.showWarning = showWarning;
window.showInfo = showInfo;
window.checkOverdueItems = checkOverdueItems;
